package com.china08.yxyapi.api.manage.sch.platform.users.teacher;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.entity.db.lessons.YxyLessonsSchoolLessonChapter;
import com.china08.yxyapi.entity.db.lessons.YxyLessonsSchoolLessonItem;
import com.china08.yxyapi.entity.db.lessons.YxyLessonsTopicLessonChapter;
import com.china08.yxyapi.entity.db.lessons.YxyLessonsTopicLessonItem;
import com.china08.yxyapi.entity.db.lessons.YxyLessonsVideo;
import com.china08.yxyapi.model.YxyApiPageReqModel;
import com.china08.yxyapi.model.YxyApiRespModel;
import com.china08.yxyapi.repository.db.YxyLessonsSchoolLessonChapterRepository;
import com.china08.yxyapi.repository.db.YxyLessonsSchoolLessonItemRepository;
import com.china08.yxyapi.repository.db.YxyLessonsTopicLessonChapterRepository;
import com.china08.yxyapi.repository.db.YxyLessonsTopicLessonItemRepository;
import com.china08.yxyapi.repository.db.YxyLessonsVideoRepository;
import com.china08.yxyapi.util.YxyResUtil;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(tags = { "v01", "教师课程-章节" })
@CrossOrigin
@RestController
@RequestMapping(value = "/api_yw")
public class YxyLessonsTeaChapterController extends YxyApiBaseController {

    @Autowired
    private YxyLessonsTopicLessonChapterRepository yxyLessonsTopicLessonChapterRepository;

    @Autowired
    private YxyLessonsTopicLessonItemRepository yxyLessonsTopicLessonItemRepository;

    @Autowired
    private YxyLessonsSchoolLessonChapterRepository yxyLessonsSchoolLessonChapterRepository;

    @Autowired
    private YxyLessonsSchoolLessonItemRepository yxyLessonsSchoolLessonItemRepository;

    @Autowired
    private YxyLessonsVideoRepository yxyLessonsVideoRepository;

    @ApiOperation(value = "教师课程-章节列表")
    @RequestMapping(value = "/manage/tec/lessons/tea/chapter/list.v", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Page<RespModel> process(HttpServletRequest request, HttpServletResponse response, @RequestBody PageReqModel reqModel) throws JsonParseException, JsonMappingException, IOException {
        Pageable pageable = new PageRequest(reqModel.page, reqModel.size);// 默认时间倒序排列
        List<RespModel> respModels = new ArrayList<RespModel>();
        if (reqModel.clzss == 1) {// 校本
            Page<YxyLessonsSchoolLessonChapter> quePage = null;
            try {
                // 编辑章节
                if (!"".equals(reqModel.lessonId) && !"".equals(reqModel.chapterId) && reqModel.chapterId != null) {
                    YxyLessonsSchoolLessonChapter chapter = yxyLessonsSchoolLessonChapterRepository.findOne(reqModel.chapterId);
                    RespModel rm = new RespModel();
                    rm.setIntro(chapter.getIntro());
                    rm.setTitle(chapter.getTitle());
                    rm.setOrderNum(chapter.getOrderNum());
                    rm.setId(chapter.getId());
                    respModels.add(rm);
                }
                // 章节列表
                if (!"".equals(reqModel.lessonId) && ("".equals(reqModel.chapterId) || reqModel.chapterId == null)) {
                    List<YxyLessonsSchoolLessonItem> items = yxyLessonsSchoolLessonItemRepository.findLessonItemsrByLessonId(reqModel.lessonId, 2);
                    List<YxyLessonsSchoolLessonChapter> chapters = yxyLessonsSchoolLessonChapterRepository.findLessonChapterByLessonId(reqModel.lessonId);
                    if (!chapters.isEmpty()) {
                        chapters.forEach((YxyLessonsSchoolLessonChapter chapter) -> {
                            RespModel rm = rmSchLesson(chapter, items, reqModel);
                            respModels.add(rm);
                        });
                    }
                }
            } catch (Exception e) {
                RespModel rm = new RespModel();
                rm.setMessage(e.getMessage());
                respModels.add(rm);
                e.printStackTrace();
            }
        } else {
            Page<YxyLessonsTopicLessonChapter> quePage = null;
            try {
                // 编辑章节
                if (!"".equals(reqModel.lessonId) && !"".equals(reqModel.chapterId) && reqModel.chapterId != null) {
                    YxyLessonsTopicLessonChapter chapter = yxyLessonsTopicLessonChapterRepository.findOne(reqModel.chapterId);
                    RespModel rm = new RespModel();
                    rm.setIntro(chapter.getIntro());
                    rm.setTitle(chapter.getTitle());
                    rm.setOrderNum(chapter.getOrderNum());
                    rm.setId(chapter.getId());
                    respModels.add(rm);
                }
                // 章节列表
                if (!"".equals(reqModel.lessonId) && ("".equals(reqModel.chapterId) || reqModel.chapterId == null)) {
                    List<YxyLessonsTopicLessonItem> items = yxyLessonsTopicLessonItemRepository.findLessonItemsrByLessonId(reqModel.lessonId, reqModel.status);
                    List<YxyLessonsTopicLessonChapter> chapters = yxyLessonsTopicLessonChapterRepository.findLessonChapterByLessonId(reqModel.lessonId);
                    if (!chapters.isEmpty()) {
                        chapters.forEach((YxyLessonsTopicLessonChapter chapter) -> {
                            respModels.add(rmTopicLesson(chapter, items, reqModel));
                        });
                    }
                }
            } catch (Exception e) {
                RespModel rm = new RespModel();
                rm.setMessage(e.getMessage());
                respModels.add(rm);
                e.printStackTrace();
            }
        }
        // 分页返回
        Page<RespModel> respPage = new PageImpl<YxyLessonsTeaChapterController.RespModel>(respModels, pageable, 1);
        return respPage;
    }

    @ApiOperation(value = "教师课程-章节添加")
    @RequestMapping(value = "/manage/tec/lessons/tea/chapter/create1.e", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Page<RespModel> create(HttpServletRequest request, HttpServletResponse response, @RequestBody PageReqModel reqModel) throws JsonParseException, JsonMappingException, IOException {
        List<RespModel> respModels = new ArrayList<RespModel>();
        String author = getProfile(request, response).getUserNick();
        if (reqModel.clzss == 1) {// 校本
            try {
                if (!"".equals(reqModel.lessonId)) {
                    YxyLessonsSchoolLessonChapter chapter = new YxyLessonsSchoolLessonChapter();
                    Integer num = yxyLessonsSchoolLessonChapterRepository.findMaxOrderNumLessonChapterByLessonId(reqModel.lessonId);
                    Integer orderNum = 0;
                    if (num == null) {
                        orderNum = 1;
                    } else {
                        orderNum = num + 1;
                    }
                    chapter.setLessonId(reqModel.lessonId);
                    chapter.setIntro(reqModel.intro); // 简介
                    chapter.setTitle(reqModel.title); // 添加章节
                    chapter.setOrderNum(orderNum);
                    chapter.setCreatedBy(author);
                    yxyLessonsSchoolLessonChapterRepository.saveAndFlush(chapter);
                    RespModel rm = new RespModel();
                    rm.setIntro(chapter.getIntro());
                    rm.setTitle(chapter.getTitle());
                    rm.setId(chapter.getId());
                    rm.setLessonId(chapter.getLessonId());
                    respModels.add(rm);
                }
            } catch (Exception e) {
                RespModel rm = new RespModel();
                rm.setMessage(e.getMessage());
                respModels.add(rm);
                e.printStackTrace();
            }
            // 分页返回
            Page<RespModel> respPage = new PageImpl<YxyLessonsTeaChapterController.RespModel>(respModels, null, 1);
            return respPage;
        } else {
            try {
                if (!"".equals(reqModel.lessonId)) {
                    YxyLessonsTopicLessonChapter chapter = new YxyLessonsTopicLessonChapter();
                    Integer num = yxyLessonsTopicLessonChapterRepository.findMaxOrderNumLessonChapterByLessonId(reqModel.lessonId);
                    Integer orderNum = 0;
                    if (num == null) {
                        orderNum = 1;
                    } else {
                        orderNum = num + 1;
                    }
                    chapter.setLessonId(reqModel.lessonId);
                    chapter.setIntro(reqModel.intro); // 简介
                    chapter.setTitle(reqModel.title); // 添加章节
                    chapter.setOrderNum(orderNum);
                    yxyLessonsTopicLessonChapterRepository.saveAndFlush(chapter);
                    RespModel rm = new RespModel();
                    rm.setIntro(chapter.getIntro());
                    rm.setTitle(chapter.getTitle());
                    rm.setId(chapter.getId());
                    rm.setLessonId(chapter.getLessonId());
                    respModels.add(rm);
                }
            } catch (Exception e) {
                RespModel rm = new RespModel();
                rm.setMessage(e.getMessage());
                respModels.add(rm);
                e.printStackTrace();
            }
            // 分页返回
            Page<RespModel> respPage = new PageImpl<YxyLessonsTeaChapterController.RespModel>(respModels, null, 1);
            return respPage;
        }
    }

    @ApiOperation(value = "教师课程-章节编辑")
    @RequestMapping(value = "/manage/tec/lessons/tea/chapter/update.e", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Page<RespModel> update(HttpServletRequest request, HttpServletResponse response, @RequestBody PageReqModel reqModel) throws JsonParseException, JsonMappingException, IOException {
        String author = getProfile(request, response).getUserNick();
        List<RespModel> respModels = new ArrayList<RespModel>();
        if (reqModel.clzss == 1) {// 校本
            try {
                if (!"".equals(reqModel.lessonId) && !"".equals(reqModel.chapterId)) {
                    YxyLessonsSchoolLessonChapter chapter = new YxyLessonsSchoolLessonChapter();
                    chapter.setLessonId(reqModel.lessonId);
                    chapter.setIntro(reqModel.intro); // 简介
                    chapter.setTitle(reqModel.title);
                    chapter.setId(reqModel.chapterId);
                    chapter.setLastModifiedBy(author);
                    yxyLessonsSchoolLessonChapterRepository.saveAndFlush(chapter);
                    RespModel rm = new RespModel();
                    rm.setIntro(chapter.getIntro());
                    rm.setTitle(chapter.getTitle());
                    rm.setId(chapter.getId());
                    rm.setLessonId(chapter.getLessonId());
                    respModels.add(rm);
                }
            } catch (Exception e) {
                RespModel rm = new RespModel();
                rm.setMessage(e.getMessage());
                respModels.add(rm);
                e.printStackTrace();
            }
            // 分页返回
            Page<RespModel> respPage = new PageImpl<YxyLessonsTeaChapterController.RespModel>(respModels, null, 1);
            return respPage;
        } else {
            try {
                if (!"".equals(reqModel.lessonId) && !"".equals(reqModel.chapterId)) {
                    YxyLessonsTopicLessonChapter chapter = new YxyLessonsTopicLessonChapter();
                    chapter.setLessonId(reqModel.lessonId);
                    chapter.setIntro(reqModel.intro); // 简介
                    chapter.setTitle(reqModel.title);
                    chapter.setId(reqModel.chapterId);
                    yxyLessonsTopicLessonChapterRepository.saveAndFlush(chapter);
                    RespModel rm = new RespModel();
                    rm.setIntro(chapter.getIntro());
                    rm.setTitle(chapter.getTitle());
                    rm.setId(chapter.getId());
                    rm.setLessonId(chapter.getLessonId());
                    respModels.add(rm);
                }
            } catch (Exception e) {
                RespModel rm = new RespModel();
                rm.setMessage(e.getMessage());
                respModels.add(rm);
                e.printStackTrace();
            }
            // 分页返回
            Page<RespModel> respPage = new PageImpl<YxyLessonsTeaChapterController.RespModel>(respModels, null, 1);
            return respPage;
        }

    }

    @ApiOperation(value = "教师课程-章节删除")
    @RequestMapping(value = "/manage/tec/lessons/tea/chapter/delete.e", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Page<RespModel> delete(HttpServletRequest request, HttpServletResponse response, @RequestBody PageReqModel reqModel) throws JsonParseException, JsonMappingException, IOException {
        List<RespModel> respModels = new ArrayList<RespModel>();
        if (reqModel.clzss == 1) {// 校本
            try {
                if (!"".equals(reqModel.lessonId) && !"".equals(reqModel.chapterId)) {
                    YxyLessonsSchoolLessonChapter chapter = yxyLessonsSchoolLessonChapterRepository.findOne(reqModel.chapterId);
                    if (chapter != null) {
                        RespModel rm = new RespModel();
                        rm.setIntro(chapter.getIntro());
                        rm.setTitle(chapter.getTitle());
                        rm.setId(chapter.getId());
                        rm.setLessonId(chapter.getLessonId());
                        respModels.add(rm);
                        yxyLessonsSchoolLessonChapterRepository.delete(reqModel.chapterId);
                    }
                }
            } catch (Exception e) {
                RespModel rm = new RespModel();
                rm.setMessage(e.getMessage());
                respModels.add(rm);
                e.printStackTrace();
            }
        } else {
            try {
                if (!"".equals(reqModel.lessonId) && !"".equals(reqModel.chapterId)) {
                    YxyLessonsTopicLessonChapter chapter = yxyLessonsTopicLessonChapterRepository.findOne(reqModel.chapterId);
                    if (chapter != null) {
                        RespModel rm = new RespModel();
                        rm.setIntro(chapter.getIntro());
                        rm.setTitle(chapter.getTitle());
                        rm.setId(chapter.getId());
                        rm.setLessonId(chapter.getLessonId());
                        respModels.add(rm);
                        yxyLessonsTopicLessonChapterRepository.delete(reqModel.chapterId);
                    }
                }
            } catch (Exception e) {
                RespModel rm = new RespModel();
                rm.setMessage(e.getMessage());
                respModels.add(rm);
                e.printStackTrace();
            }
        }
        // 分页返回
        Page<RespModel> respPage = new PageImpl<YxyLessonsTeaChapterController.RespModel>(respModels, null, 1);
        return respPage;
    }

    // 分页请求
    protected static class PageReqModel extends YxyApiPageReqModel {
        public String chapterId;
        public String lessonId; // 课程id
        public String catalogId;// 分类id
        public String title;
        public String intro;
        public Integer status;
        public Integer clzss;// 1校本 2专题
    }

    public static class Item {
        private String pid; // 章节
        private String id; // 课时
        private String title;
        private String intro;
        private Integer status;
        private Integer preview;
        private Integer orderNum;
        private Integer duration;// 时长
        private String videoId; // 视频ID
        private String videoName; // 视频名称
        private String durationName;// 时长

        /**
         * @return the pid
         */
        public String getPid() {
            return pid;
        }

        /**
         * @param pid
         *            the pid to set
         */
        public void setPid(String pid) {
            this.pid = pid;
        }

        /**
         * @return the id
         */
        public String getId() {
            return id;
        }

        /**
         * @param id
         *            the id to set
         */
        public void setId(String id) {
            this.id = id;
        }

        /**
         * @return the title
         */
        public String getTitle() {
            return title;
        }

        /**
         * @param title
         *            the title to set
         */
        public void setTitle(String title) {
            this.title = title;
        }

        /**
         * @return the intro
         */
        public String getIntro() {
            return intro;
        }

        /**
         * @param intro
         *            the intro to set
         */
        public void setIntro(String intro) {
            this.intro = intro;
        }

        /**
         * @return the status
         */
        public Integer getStatus() {
            return status;
        }

        /**
         * @param status
         *            the status to set
         */
        public void setStatus(Integer status) {
            this.status = status;
        }

        /**
         * @return the preview
         */
        public Integer getPreview() {
            return preview;
        }

        /**
         * @param preview
         *            the preview to set
         */
        public void setPreview(Integer preview) {
            this.preview = preview;
        }

        /**
         * @return the orderNum
         */
        public Integer getOrderNum() {
            return orderNum;
        }

        /**
         * @param orderNum
         *            the orderNum to set
         */
        public void setOrderNum(Integer orderNum) {
            this.orderNum = orderNum;
        }

        /**
         * @return the duration
         */
        public Integer getDuration() {
            return duration;
        }

        /**
         * @param duration
         *            the duration to set
         */
        public void setDuration(Integer duration) {
            this.duration = duration;
        }

        /**
         * @return the videoId
         */
        public String getVideoId() {
            return videoId;
        }

        /**
         * @param videoId
         *            the videoId to set
         */
        public void setVideoId(String videoId) {
            this.videoId = videoId;
        }

        /**
         * @return the videoName
         */
        public String getVideoName() {
            return videoName;
        }

        /**
         * @param videoName
         *            the videoName to set
         */
        public void setVideoName(String videoName) {
            this.videoName = videoName;
        }

        /**
         * @return the durationName
         */
        public String getDurationName() {
            return durationName;
        }

        /**
         * @param durationName
         *            the durationName to set
         */
        public void setDurationName(String durationName) {
            this.durationName = durationName;
        }

    }

    protected static class RespModel extends YxyApiRespModel {
        private String id;
        private String lessonId;
        private String catalogId;// 目录id

        private String title;// 章节名称

        private String intro;// 简介

        private String lesson; // 课程
        private Integer orderNum;
        public Integer status;

        private List<Item> items = new ArrayList<Item>();

        /**
         * @return the id
         */
        public String getId() {
            return id;
        }

        /**
         * @param id
         *            the id to set
         */
        public void setId(String id) {
            this.id = id;
        }

        /**
         * @return the catalogId
         */
        public String getCatalogId() {
            return catalogId;
        }

        /**
         * @param catalogId
         *            the catalogId to set
         */
        public void setCatalogId(String catalogId) {
            this.catalogId = catalogId;
        }

        /**
         * @return the title
         */
        public String getTitle() {
            return title;
        }

        /**
         * @param title
         *            the title to set
         */
        public void setTitle(String title) {
            this.title = title;
        }

        /**
         * @return the intro
         */
        public String getIntro() {
            return intro;
        }

        /**
         * @param intro
         *            the intro to set
         */
        public void setIntro(String intro) {
            this.intro = intro;
        }

        /**
         * @return the lesson
         */
        public String getLesson() {
            return lesson;
        }

        /**
         * @param lesson
         *            the lesson to set
         */
        public void setLesson(String lesson) {
            this.lesson = lesson;
        }

        /**
         * @return the items
         */
        public List<Item> getItems() {
            return items;
        }

        /**
         * @param items
         *            the items to set
         */
        public void setItems(List<Item> items) {
            this.items = items;
        }

        /**
         * @return the lessonId
         */
        public String getLessonId() {
            return lessonId;
        }

        /**
         * @param lessonId
         *            the lessonId to set
         */
        public void setLessonId(String lessonId) {
            this.lessonId = lessonId;
        }

        /**
         * @return the orderNum
         */
        public Integer getOrderNum() {
            return orderNum;
        }

        /**
         * @param orderNum
         *            the orderNum to set
         */
        public void setOrderNum(Integer orderNum) {
            this.orderNum = orderNum;
        }

    }

    public RespModel rmTopicLesson(YxyLessonsTopicLessonChapter chapter, List<YxyLessonsTopicLessonItem> items, PageReqModel reqModel) {
        RespModel rm = new RespModel();
        rm.setIntro(chapter.getIntro());
        rm.setTitle(chapter.getTitle());
        rm.setOrderNum(chapter.getOrderNum());
        rm.setLessonId(chapter.getLessonId());
        rm.setId(chapter.getId());
        rm.status = reqModel.status;
        if (!items.isEmpty()) {
            items.forEach((YxyLessonsTopicLessonItem itm) -> {
                if (chapter.getId().equals(itm.getChapterId())) {
                    Item im = new Item();
                    try {
                        if (itm.getVideoId() != null) {
                            YxyLessonsVideo vid = yxyLessonsVideoRepository.findById(itm.getVideoId());
                            im.setDuration(vid.getDuration());
                            im.setDurationName(YxyResUtil.getDurationToString(vid.getDuration()));
                            im.setVideoName(vid.getFileName());
                            im.setVideoId(itm.getVideoId());
                        } else {
                            im.setDuration(0);
                        }
                    } catch (Exception e) {
                    }
                    im.setId(itm.getId());
                    im.setIntro(itm.getIntro());
                    im.setPid(itm.getChapterId());
                    im.setTitle(itm.getTitle());
                    im.setOrderNum(itm.getOrderNum());
                    im.setPreview(itm.getPreview());
                    rm.getItems().add(im);
                }
            });
        }
        if (rm.getItems().size() == 0) {
            Item im = new Item();
            im.setId(chapter.getId());
            im.setPid(chapter.getId());
            im.setOrderNum(0);
            rm.getItems().add(im);
        }
        return rm;
    }

    public RespModel rmSchLesson(YxyLessonsSchoolLessonChapter chapter, List<YxyLessonsSchoolLessonItem> items, PageReqModel reqModel) {
        RespModel rm = new RespModel();
        rm.setIntro(chapter.getIntro());
        rm.setTitle(chapter.getTitle());
        rm.setOrderNum(chapter.getOrderNum());
        rm.setLessonId(chapter.getLessonId());
        rm.setId(chapter.getId());
        rm.status = reqModel.status;
        if (!items.isEmpty()) {
            items.forEach((YxyLessonsSchoolLessonItem itm) -> {
                if (chapter.getId().equals(itm.getChapterId())) {
                    Item im = new Item();
                    try {
                        if (itm.getVideoId() != null) {
                            YxyLessonsVideo vid = yxyLessonsVideoRepository.findById(itm.getVideoId());
                            im.setDuration(vid.getDuration());
                            im.setDurationName(YxyResUtil.getDurationToString(vid.getDuration()));
                            im.setVideoName(vid.getFileName());
                            im.setVideoId(itm.getVideoId());
                        } else {
                            im.setDuration(0);
                        }
                    } catch (Exception e) {
                    }
                    im.setId(itm.getId());
                    im.setIntro(itm.getIntro());
                    im.setPid(itm.getChapterId());
                    im.setTitle(itm.getTitle());
                    im.setOrderNum(itm.getOrderNum());
                    im.setPreview(itm.getPreview());
                    im.setStatus(itm.getStatus());
                    rm.getItems().add(im);
                }
            });
        }
        if (rm.getItems().size() == 0) {
            Item im = new Item();
            im.setId(chapter.getId());
            im.setPid(chapter.getId());
            im.setOrderNum(0);
            rm.getItems().add(im);
        }
        return rm;
    }
}
